import React, { useEffect, useRef, useState, useImperativeHandle, forwardRef } from "react";
import BScroll from "@better-scroll/core";
import ObserveDOM from "@better-scroll/observe-dom";
import PullUp from "@better-scroll/pull-up";
import { uniqueId } from "lodash";
import PropTypes from "prop-types";


/**
 * 滚动组件 长列表可用
 */

BScroll.use(ObserveDOM);

let timer;

const Wrap = forwardRef((props, myRef) => {
    const wrapper = useRef(null);
    const [bscroll, setbscroll] = useState();

    function initBScroll() {
        timer = setTimeout(() => {
            setbscroll(() => {
                BScroll.use(PullUp);
                const bscroll = new BScroll(wrapper.current, {
                    click: true,
                    scrollX: true,
                    observeDOM: true,
                    // observeImage: true,
                    pullUpLoad: true,
                    useTransition: false,
                    mouseWheel: true,
                });
                const pullingUp = props.pullingUp;
                if (pullingUp) {
                    const finishPull = () => {
                        return new Promise((resolve, reject) => {
                            pullingUp();
                            resolve();
                        }).then(res => {
                            bscroll.finishPullUp();
                            bscroll.refresh();
                        });
                    };
                    bscroll.stop();
                    bscroll.on("pullingUp", finishPull);
                }
                return bscroll;
            });
        }, 200);
    }

    useImperativeHandle(myRef, () => ({
        bscroll,
    }));

    useEffect(() => {
        initBScroll();
        return () => {
            if (bscroll && bscroll.destroy) {
                bscroll.destroy();
            }
            clearTimeout(timer);
        };
    }, []);

    return (
        <div className={`${uniqueId("scroll-")} bScroll-container`} ref={wrapper}>
            {props.children}
        </div>
    );
});

Wrap.displayName = "Wrap";
Wrap.propTypes = {
    pullingUp: PropTypes.func,
    children: PropTypes.element,
};

export default Wrap;
